package de.tordroid.ui;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.Spinner;
import android.widget.Toast;
import de.tordroid.R;
import de.tordroid.core.Database;
import de.tordroid.core.Engine;
import de.tordroid.core.adapter.CharacterSpinnerAdapter;
import de.tordroid.core.adapter.MyExpandableListAdapter;
import de.tordroid.core.listener.MyTabListener;

public class MainActivity extends Activity {
    
    private static String className = "MainActivity";
    private ExpandableListView storyListView;
    private MyExpandableListAdapter storyAdapter;
    private ActionBar actionBar;
    private CharacterSpinnerAdapter characterAdapter;
    private Spinner characterSpinner;
    //private MenuItem characterChooser;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(className, "Initializing Profile");
        Engine.init();
        setContentView(R.layout.main);
        
        initActionView();
        initListView();
        initActionBar();
        initContentFragment(savedInstanceState);
    }
    
    private void initActionView() {
        this.characterAdapter = new CharacterSpinnerAdapter(this);
    }
    
    private void initCharacterChooser(Menu menu) {
        //this.characterChooser = menu.findItem(R.id.menu_select_character);
        this.characterSpinner = (Spinner) menu.findItem(R.id.menu_select_character).getActionView();
        characterSpinner.setAdapter(characterAdapter);
        
        this.characterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getApplicationContext(), characterAdapter.getItem(position).getSurname(), Toast.LENGTH_SHORT).show();
                // Call specific character fragment
                de.tordroid.model.Character character = characterAdapter.getItem(position);
                Engine.setCurrentCharacter(character);
                
                // Reset Storylist
                storyAdapter = new MyExpandableListAdapter(getApplicationContext());
                storyListView.setAdapter(storyAdapter);
                
                Log.d(className + ".onChildClick", "Character: " + Engine.getCharacterFullname());;
                changeFragment(OverviewFragment.newInstance(), getParent());                
            }
            
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        
        if (!Engine.getCharacters().isEmpty()) {
            characterSpinner.setSelection(0);
        }
    }
    
    private void initListView() {
        this.storyListView = (ExpandableListView) findViewById(R.id.list);
        
        storyAdapter = new MyExpandableListAdapter(this);
        
        storyListView.setAdapter(storyAdapter);
        
        storyListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                if (!parent.isGroupExpanded(groupPosition)) {
                    parent.expandGroup(groupPosition, true);
                } else {
                    parent.collapseGroup(groupPosition);
                }
                
                Engine.setCurrentStory(storyAdapter.getGroup(groupPosition));
                Log.d(className + ".onChildClick", "Story: " + Engine.getStoryTitel());;
                
                StoryboardFragment newFragment = StoryboardFragment.newInstance();
                changeFragment(newFragment, getParent());
                storyAdapter.notifyDataSetChanged();
                return true;
            }
        });
        
        storyListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Engine.setCurrentStory(storyAdapter.getChild(groupPosition, childPosition));
                Log.d(className + ".onChildClick", "SubStory: " + Engine.getStoryTitel());
                
                StoryboardFragment newFragment = StoryboardFragment.newInstance();
                changeFragment(newFragment, getParent());
                storyAdapter.notifyDataSetChanged();
                return true;
            }
        });
    }
    
    private void changeFragment(Fragment fragment, Activity activity) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
        if (fragment == null) {
            Engine.CURRENT_FRAGMENT = fragment.getClass().getName();
            fragment = Fragment.instantiate(activity, Engine.CURRENT_FRAGMENT);
            
            ft.replace(Engine.FRAG_ID, fragment, Engine.FRAG_TAG).commit();
            Log.d("Changing Fragment", Engine.CURRENT_FRAGMENT);
        } else {
            // Using existing Fragment
            ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_in);
            Log.d("Changing Fragment", "attaching: " + Engine.CURRENT_FRAGMENT + " to: " + fragment.getClass().getName());
            Engine.CURRENT_FRAGMENT = fragment.getClass().getName();
            if (fragment.isDetached()) {
                fragment = Fragment.instantiate(activity, Engine.CURRENT_FRAGMENT);
                ft.attach(fragment).commit();
            } else {
                ft.remove(getFragmentManager().findFragmentById(R.id.content));
                ft.replace(Engine.FRAG_ID, fragment, Engine.FRAG_TAG).commit();
            }
        }
        
    }
    
    private void initContentFragment(Bundle savedInstanceState) {
        if (findViewById(R.id.content) != null) {
            if (savedInstanceState != null) {
                return;
            }
            OverviewFragment firstFragment = new OverviewFragment();
            getFragmentManager().beginTransaction().add(R.id.content, firstFragment).commit();
        }
    }
    
    private void initActionBar() {
        // ActionBar
        actionBar = this.getActionBar();
        actionBar.setDisplayShowTitleEnabled(
                false);
        actionBar.setDisplayShowHomeEnabled(
                false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);


        // Overview Fragment
        ActionBar.Tab tab = actionBar.newTab().setText(R.string.bar_home).setTabListener(
                new MyTabListener<OverviewFragment>(this, OverviewFragment.class));
        tab.setIcon(R.drawable.ic_home);
        actionBar.addTab(tab);


        // Character Details Fragment
        tab = actionBar.newTab().setText(R.string.bar_character).setTabListener(
                new MyTabListener<CharacterFragment>(this, CharacterFragment.class));
        tab.setIcon(R.drawable.ic_character);
        actionBar.addTab(tab);


        // Storyboard Fragment
        tab = actionBar.newTab().setText(R.string.bar_storyboard).setTabListener(
                new MyTabListener<StoryboardFragment>(this, StoryboardFragment.class));
        tab.setIcon(R.drawable.ic_book);
        actionBar.addTab(tab);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.clear();
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        initCharacterChooser(menu);
        super.onCreateOptionsMenu(menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add:
                Engine.addCharacter();
                this.storyAdapter.notifyDataSetChanged();
                this.characterAdapter.notifyDataSetChanged();
                return true;
            case R.id.menu_delete:
                Engine.removeCharacter(Engine.getCurrentCharacter());
                this.storyAdapter.notifyDataSetChanged();
                this.characterAdapter.notifyDataSetChanged();
                return true;
            case R.id.menu_save:
                Database.save();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
